package jicheng;

import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.xx.jicheng.entity.Product;
import com.xx.jicheng.entity.ProductAttr;
import com.xx.jicheng.mapper.ProductMapper;

public class SpiderProductDetail {
	

	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");
		ProductMapper productMapper = context.getBean(ProductMapper.class);

		

		List<Product> list = productMapper.findAll();
		for (int i = 0; i < list.size(); i++) {
			System.out.println(i);
			Product p = list.get(i);
			try {
//				System.out.println("process file" + p.getId());
				Document doc = Jsoup.connect(p.getHref()).get();
				String code = doc.select(".equi_name_top i").attr("class");

				Elements elements = doc.select(".chanpincanshu p.tobeknown");
				for (Element e : elements) {
					String[] attr = e.text().split("： ");
					// System.out.println(attr[0] + "： " + attr[1]);
					ProductAttr pa = new ProductAttr();
					pa.setPid(p.getId());
					pa.setName(attr[0]);
					if(attr.length>=2){
						pa.setValue(attr[1]);
					} else {
						pa.setValue("");
					}
					productMapper.saveProductAttr(pa);
				}
				String detail = doc.select(".cp-xiangqing img").attr("src").replaceAll("\\s+", "");
//				images.put(p.getImg());
//				images.put(detail);
				// System.out.println(code);
				// System.out.println(detail);
				p.setCode(code);
				p.setDetail(detail);
				productMapper.updateDetail(p);
			} catch (Exception e1) {
				System.err.println("------error====" + p.getId());
				e1.printStackTrace();
			}
		}
		context.close();
	}

}
